<template>
  <div class="table2">
    <div class="pl-20n pt-20 flex-col" v-if="!creatSuccess">
      <a-steps :current="stepCurrent" :status="stepStatus" style="width: 30%; min-width: 500px" class="mb-20">
        <a-step>
          创建任务
          <template #icon>
            <icon-tool />
          </template>
        </a-step>
        <a-step>
          分配用户
          <template #icon>
            <icon-idcard />
          </template>
        </a-step>
        <!-- <a-step>
        批量代发
        <template #icon>
            <icon-storage />
        </template>
      </a-step> -->
      </a-steps>
      <a-form
        v-if="stepCurrent === 1"
        ref="formRef"
        style="width: 30%; min-width: 500px"
        label-align="left"
        :model="listParams"
        class="mt-30"
      >
        <a-form-item
          field="payAccount"
          label="打款平台："
          :rules="[{ required: true, message: '请选择打款平台' }]"
          :validate-trigger="['change', 'clear', 'remove', 'input-value-change']"
        >
          <a-select v-model="listParams.payAccount" @change="payAccountChange" placeholder="请选择">
            <a-option
              v-for="item in paymentMethodList"
              :key="item.id"
              :value="item.id"
              :label="item.account"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="payType"
          label="收款方式："
          :rules="[{ required: true, message: '请选择收款方式' }]"
          :validate-trigger="['change', 'clear', 'remove', 'input-value-change']"
        >
          <a-select v-model="listParams.payType" placeholder="请选择">
            <a-option :value="3" :disabled="listParams.payAccount == 11" label="支付宝"></a-option>
            <a-option :value="1" label="小额打款"></a-option>
            <a-option :value="4" label="银行卡"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="submitStartAt"
          label="开始时间："
          :rules="[{ required: true, message: '请选择提现开始时间' }]"
          :validate-trigger="['change', 'clear', 'ok', 'select']"
        >
          <a-date-picker show-time v-model="listParams.submitStartAt" placeholder="请选择提现开始时间"></a-date-picker>
        </a-form-item>
        <a-form-item
          field="submitStartEnd"
          label="结束时间："
          :rules="[{ required: true, message: '请选择提现结束时间' }]"
          :validate-trigger="['change', 'clear', 'ok', 'select']"
        >
          <a-date-picker show-time v-model="listParams.submitStartEnd" placeholder="请选择提现结束时间"></a-date-picker>
        </a-form-item>
        <a-form-item
          field="amount"
          label="提现金额："
          :rules="[
            {
              required: true,
              validator: amountValidator,
              trigger: 'change'
            }
          ]"
        >
          <a-input-group compact>
            <a-input-number v-model="listParams.minAmount" :min="0" class="w-45n" placeholder="最低提现金额" />
            <a-input style="width: 40px; pointer-events: none" placeholder="~" disabled />
            <a-input-number v-model="listParams.maxAmount" :min="1" class="w-45n" placeholder="最高提现金额" />
          </a-input-group>
        </a-form-item>
        <a-form-item field="alert" hide-label v-if="showTip">
          <a-alert>
            共筛选 <span class="font-bold">{{ info.totalCount }}</span> 个用户，
            <span class="font-bold">{{ info.totalAmount }}元</span> 佣金待打款！
          </a-alert>
        </a-form-item>
        <a-form-item
          field="limit"
          label="打款人数："
          :rules="[{ required: true, message: '请输入打款人数' }]"
          :validate-trigger="['change', 'input', 'clear', 'blur']"
        >
          <a-input-number v-model="listParams.limit" placeholder="最多可输入500人" :min="1" :max="500"></a-input-number>
        </a-form-item>
      </a-form>
      <div class="w-full flex-1" v-else-if="stepCurrent === 2">
        <GiTable
          row-key="id"
          id="payment"
          v-model:columns="columns"
          :loading="loading"
          :data="tableData"
          :pagination="{
            total: tableData.length,
            showPageSize: true,
            showTotal: true,
            pageSize: 10
          }"
          :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
          @refresh="getTableData"
        >
          <template #custom-extra>
            <a-input-search
              v-model="listParams.keyword"
              :style="{ width: '320px' }"
              placeholder="请输入邀请码/手机号搜索"
              search-button
              @search="getTableData()"
            >
              <template #button-icon>
                <icon-search />
              </template>
              <template #button-default> 搜索 </template>
            </a-input-search>
          </template>
          <template #user="{ record }">
            <div class="flex-col">
              <span>邀请码：{{ record.inviteCode }}</span>
              <span>手机号：{{ record.mobile }}</span>
            </div>
          </template>
          <template #info="{ record }">
            <div class="flex-col">
              <span
                >{{ record.withdrawalAccountInfo.withdrawalMethod == 3 ? '支付宝' : '银行卡' }}：{{
                  record.withdrawalAccountInfo.withdrawalName
                }}</span
              >
              <span>账号：{{ record.withdrawalAccountInfo.withdrawalAccount }}</span>
            </div>
          </template>
        </GiTable>
      </div>
      <a-space class="mt-20">
        <a-button type="secondary" :disabled="stepCurrent <= 1" @click="onPrev"> <IconLeft /> 上一步 </a-button>
        <a-button type="primary" :disabled="stepCurrent == 2" @click="onNext"> 下一步 <IconRight /> </a-button>
        <a-button type="primary" v-if="stepCurrent == 2" @click="onOk" :loading="submitLoading"> 提交 </a-button>
      </a-space>
    </div>
    <div v-else class="pt-30 mx-auto w-fit">
      <a-result status="success" title="创建成功">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="toTaskList">前往查看</a-button>
            <a-button @click="creatAgain">再次创建</a-button>
          </a-space>
        </template>
      </a-result>
    </div>
  </div>
</template>

<script setup>
import { getTaskConditionInfo, financeCreateTask, getTaskConditionUsers, paymentMethod } from '@/apis'
import $bus from '@/utils/bus'
defineOptions({ name: 'payment' })
const router = useRouter()
const formRef = ref()
const stepCurrent = ref(1)
const stepStatus = ref('process')
const loading = ref(false)
const submitLoading = ref(false)
const creatSuccess = ref(false)
const listParams = reactive({
  payAccount: undefined,
  payType: undefined,
  minAmount: undefined,
  maxAmount: undefined,
  submitStartAt: undefined,
  submitStartEnd: undefined,
  limit: undefined,
  keyword: undefined
})
const columns = ref([
  {
    title: '提现用户',
    width: 150,
    slotName: 'user'
  },
  {
    title: '提现金额',
    width: 130,
    dataIndex: 'withdrawalAmount'
  },
  {
    title: '提现时间',
    width: 180,
    dataIndex: 'withdrawalTime'
  },
  {
    title: '提现凭证',
    width: 150,
    dataIndex: 'withdrawalNo'
  },
  {
    title: '提现帐号',
    width: 330,
    slotName: 'info'
  }
])
const info = reactive({
  totalAmount: 0,
  totalCount: 0
})
const tableData = ref([])
const hasEmptyKey = (obj) => {
  return Object.keys(obj).some(
    (key) =>
      key !== 'limit' &&
      key !== 'page' &&
      key !== 'keyword' &&
      (obj[key] === undefined || obj[key] === null || obj[key] === '')
  )
}
const showTip = ref(false)
const paymentMethodList = ref([])

const getPaymentMethod = async () => {
  const res = await paymentMethod({ method: 2 })
  paymentMethodList.value = res.data.list
}
getPaymentMethod()
// 校验提现规则
const amountValidator = (value, cb) => {
  return new Promise((resolve) => {
    if (!listParams.minAmount) cb('请输入最低提现金额')
    if (!listParams.maxAmount) cb('请输入最高提现金额')
    resolve()
  })
}

const onPrev = () => {
  if (listParams.keyword) listParams.keyword = undefined
  stepCurrent.value = Math.max(1, stepCurrent.value - 1)
}

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await getTaskConditionUsers({ ...listParams })
    tableData.value = res.data.list
    getPaymentMethod()
  } finally {
    loading.value = false
  }
}
const onNext = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  stepCurrent.value = Math.min(2, stepCurrent.value + 1)
  getTableData()
}

// 确认提交
const onOk = async () => {
  try {
    submitLoading.value = true
    await financeCreateTask({ ...listParams })
    creatSuccess.value = true
  } finally {
    submitLoading.value = false
  }
}

//再次创建
const creatAgain = () => {
  stepCurrent.value = 1
  creatSuccess.value = false
}

watchEffect(async () => {
  const result = hasEmptyKey(listParams)
  if (result) showTip.value = false
  else {
    const res = await getTaskConditionInfo(listParams)
    info.totalAmount = res.data.totalAmount
    info.totalCount = res.data.totalCount
    showTip.value = true
  }
})

const toTaskList = () => {
  $bus.emit('financeTaskList')
  router.push({
    name: 'financeTaskList'
  })
  creatAgain()
}

const payAccountChange = (e) => {
  if (e === 11) {
    listParams.payType = 4
  }
}

onMounted(() => {
  $bus.on('financeTask', () => {
    creatAgain()
  })
})

onUnmounted(() => {
  $bus.off('financeTask')
})
</script>

<style lang="scss" scoped>
.table2 {
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  :deep(.arco-form-item-label) {
    white-space: nowrap;
  }
}
</style>
